package ms.core.gateway.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ms.core.common.Page;
import ms.core.db.mysql.QueryParam;
import ms.core.gateway.bean.SysLoginBean;
import ms.core.tool.Log4j2Tool;
import ms.core.tool.StrTool;

public class SysLoginDao extends BaseDao{

	public SysLoginDao() { super("sys_login"); }

	public void saveLoginLog(String userUid, String corpUid, String account, String ip, String location) {
		try {
			Map<String, Object> values = new HashMap<>();
			values.put("userUid", userUid);
			values.put("corpUid", corpUid);
			values.put("account", account);
			values.put("loginIp", ip);
			values.put("loginArea", location);
			values.put("loginTime", new Date());
			db.insertRecord(table, values);
		} catch (Exception e) {
			Log4j2Tool.error(SysLoginDao.class, e);
		}
	}

	/**
	 * 批量删除日志
	 * 
	 * @param uid
	 * @param list
	 * @return
	 */
	public int deleteLoginLog(String uid, List<Long> list) {
		if (StrTool.isBlank(uid) || list==null || list.size()==0)
			return 0;
		
		int ret = 0;
		for(int i=0; i<list.size(); i++) {
			String sql = String.format("delete from %s where id=? and userUid=?", table);
			if (db.executeSql(sql, new Object[] {list.get(i), uid})>0) ret++;
		}
		
		return ret;
	}

	private String getCondition(String corpUid, String account, QueryParam qp){
		String ret = "";

		if (!StrTool.isBlank(corpUid)) {
			ret += " and corpUid=?";
			qp.addParam(corpUid);
		}
		if (!StrTool.isBlank(account)) {
			ret += " and account=?";
			qp.addParam(account);
		}

		return ret;
	}

	public Page<SysLoginBean> queryLogin(String corpId, String uid, int page, int pagesize) {
		QueryParam qp = QueryParam.getInstance().setPage(page, pagesize);
		String sqlWhere = this.getCondition(corpId, uid, qp);
		String countSql = String.format("select count(*) from %s where 1>0", table) + sqlWhere;
		String querySql = String.format("select * from %s where 1>0", table) + sqlWhere+" order by loginTime desc";
		
		qp.setCntSql(countSql).setQrySql(querySql);
		return db.queryForPage(qp, SysLoginBean.class);
	}
}